package com.fangmu.transferdata.utils;

/**
 * @author created by lyl
 * @data 2022/4/3.
 * @description
 */
public class BytesUtils {
    public static int isOdd(int num) {
        return num & 0x1;
    }

    public static int HexToInt(String inHex) {
        return Integer.parseInt(inHex, 16);
    }

    public static byte HexToByte(String inHex) {
        return (byte) Integer.parseInt(inHex, 16);
    }

    public static String Byte2Hex(Byte inByte) {
        return String.format("%02x", new Object[]{inByte}).toUpperCase();
    }

    public static String ByteArrToHex(byte[] inBytArr) {
        StringBuilder strBuilder = new StringBuilder();
        int j = inBytArr.length;
        for (int i = 0; i < j; i++) {
            strBuilder.append(Byte2Hex(Byte.valueOf(inBytArr[i])));
            strBuilder.append("");
        }
        return strBuilder.toString();
    }

    public static String ByteArrToHex(byte[] inBytArr, int offset, int byteCount) {
        StringBuilder strBuilder = new StringBuilder();
        int j = byteCount;
        for (int i = offset; i < j; i++) {
            strBuilder.append(Byte2Hex(Byte.valueOf(inBytArr[i])));
        }
        return strBuilder.toString();
    }

    public static byte[] HexToByteArr(String inHex) {
        int hexlen = inHex.length();
        byte[] result;
        if (isOdd(hexlen) == 1) {
            hexlen++;
            result = new byte[hexlen / 2];
            inHex = "0" + inHex;
        } else {
            result = new byte[hexlen / 2];
        }
        int j = 0;
        for (int i = 0; i < hexlen; i += 2) {
            result[j] = HexToByte(inHex.substring(i, i + 2));
            j++;
        }
        return result;
    }

    public static String IntToHex(int num) {
        char [] sign= {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        //利用计算结果，数组角标和数组内容之间的关联性，巧妙的输出数组中的内容；
        StringBuffer s=new StringBuffer();
        //创建一个StringBuffer的对象s，与String类相似，区别是StringBuffer可以创建动态拼接的字符串。
        if(num==0) {
            System.out.print("您输入的整数转换为16进制为"+0);
        }//把num等于0这个特殊情况单独拿出来。
        while(num!=0) {
            int x=num%16;//当num不等于0时先对其求余，切记不可先除，先除的话num的值已改变
            s=s.append(sign[x]);//用StringBuffer的对象s调用append方法，将求余得到的余数写入s
            num/=16;//再求除，更新num的值，进行下一次求余
        }
        s=s.reverse();//用StringBuffer中提供的reverse方法对其进行反转，不理解反转的话可以想想十进制转换为十六进制的方法
        System.out.print(s);
        return String.valueOf(s);
    }
}
